<template>
  <div id="role" ref="role">
    <SearchForm v-model="ruleForm" :dataJ="dataJ" @search-form="searchForm" />
    <BkBtn :btnConfig="btnConfig" />
    <BkTable
      :tableHead="tableJ"
      :tableData="tableData"
      :total="total"
      :page="page"
      @getList="getList"
    />
    <el-dialog
      :visible.sync="dialogVisibleEnd"
      :close-on-click-modal="false"
      width="450px"
      :center="true"
    >
      <div slot="title" class="dialog-title">
        <span>{{ dialogTitle }}</span>
      </div>
      <el-form
        :inline="true"
        v-if="dialogVisibleEnd"
        :model="forms"
        :rules="rule"
        ref="forms"
        class="el-form-item_block"
      >
        <el-form-item
          label="角色名称"
          label-width="80px"
          prop="roleName"
          class="el-form-item"
        >
          <el-input
            v-model="forms.roleName"
            size="small"
            placeholder="请输入角色名称"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          label-width="80px"
          prop="roleDesc"
          class="el-form-item"
        >
          <el-input
            v-model="forms.roleDesc"
            type="textarea"
            size="small"
            placeholder="请输入角色描述"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          size="small"
          @click="dialogVisibleEnd = false"
          type="info"
          plain
          >取消</el-button
        >
        <el-button size="small" @click="submitform('forms')" type="primary"
          >保存</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="authSetDialog"
      :center="true"
      :before-close="dialogClose"
    >
      <div slot="title" class="dialog-title">
        <span>权限配置</span>
      </div>
      <div style="line-height: 26px">
        <div class="line">角色名称：{{ roleName }}</div>
        <div class="line">角色描述：{{ roleDesc }}</div>
        <div class="line">
          数据权限：
          <!-- <el-radio v-model="roleDefaultSign" label="1">本院</el-radio>
          <el-radio v-model="roleDefaultSign" label="2">科室</el-radio>
          <el-radio v-model="roleDefaultSign" label="3">个人</el-radio> -->
          <el-checkbox-group v-model="detailInfo.dataAuthIds">
            <el-checkbox
              v-for="item in authList"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
        <!-- <div class="line">
          默认专病库：
          <el-select v-model="detailInfo.defaultAuthId" placeholder="请选择">
            <el-option
              v-for="item in authList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div> -->
        <el-table
          class="authTable"
          ref="powerData"
          :data="powerData"
          :height="$pxtorem(500)"
          style="width: 100%; margin-bottom: 20px; margin-top: 10px"
          row-key="_id"
          border
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="menuName" label="菜单查看权限" width="220">
            <template slot-scope="scope">
              <el-checkbox
                @change="checkChange($event, scope.row)"
                v-model="scope.row.checkFlag"
                >{{ scope.row.menuName || scope.row.name }}</el-checkbox
              >
            </template>
          </el-table-column>
          <el-table-column prop="name" label="操作权限">
            <template slot-scope="scope" v-if="scope.row.menuType == 2">
              <el-checkbox-group
                v-model="scope.row.checkList"
                @change="handleChange($event, scope.row)"
              >
                <el-checkbox
                  v-for="(item, ind) in scope.row.permissions"
                  :label="item.authValue"
                  :key="ind"
                  >{{ item.authName }}</el-checkbox
                >
              </el-checkbox-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogClose" type="info" plain
          >取消</el-button
        >
        <el-button size="small" @click="submitTree()" type="primary"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getRoleLists,
  saveRole,
  updateRole,
  deleteRole,
  getAuthTree,
  saveRoleAuth,
  getRoleDetailById,
} from "@/api/login";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      // roleDefaultSign: "1",
      ruleForm: {},
      tableData: [{}],
      checkList: [],
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      //   新增 ---- 编辑
      id: "",
      dialogVisibleEnd: false,
      dialogTitle: "",
      forms: {
        roleName: "",
        roleDesc: "",
      },
      rule: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      dialogVisible: false, // 权限树弹窗
      roleName: "", // 角色名称
      roleDesc: "", // 角色描述
      // dataAuthIds: [], // 数据权限
      // defaultAuthId: "", // 默认专病库
      roleMenu: [], // 菜单权限
      roleAuth: [], // 操作权限
      powerData: [], // 权限树
      defaultProps: {
        children: "children",
        label: "menuName",
      },
      detailInfo: {
        dataAuthIds: [],
        defaultAuthId: '',
      },
      authList: [
        {
          label: "专病库A",
          value: "A",
        },
        {
          label: "专病库B",
          value: "B",
        },
        {
          label: "专病库C",
          value: "C",
        },
        {
          label: "专病库D",
          value: "D",
        },
        {
          label: "专病库E",
          value: "E",
        },
      ],
    };
  },
  computed: {
    dataJ() {
      return [
        {
          label: "角色名称",
          prop: "roleName",
          type: "input",
        },
      ];
    },
    btnConfig() {
      return [
        {
          label: "新增",
          // permissionValue: 'sys:role:create',
          Fn: this.addData,
        },
      ];
    },
    tableJ() {
      return [
        {
          prop: "roleName",
          label: "角色名称",
          sortable: false,
        },
        {
          prop: "roleDesc",
          label: "角色描述",
          sortable: false,
        },
        {
          prop: "createTime",
          label: "创建时间",
          sortable: false,
        },
        {
          label: "操作",
          width: "260px",
          btnList: [
            {
              name: "权限配置",
              type: "text",
              handleClick: (val) => {
                this.id = val.id;
                this.roleName = val.roleName;
                this.roleDesc = val.roleDesc;
                this.singleDetail(val);
              },
            },
            {
              name: "编辑",
              type: "text",
              handleClick: (val) => {
                this.editData(val);
              },
            },
            {
              name: "删除",
              type: "text",
              handleClick: (val) => {
                this.id = val.id;
                this.delData(val);
              },
            },
          ],
        },
      ];
    },
  },
  created() {},
  mounted() {
    this.getList();
    this.getAuthTreeList();
  },
  methods: {
    searchForm() {
      this.page.pageNum = 1;
      this.getList();
    },
    getList() {
      let params = {
        pageSize: this.page.pageSize,
        pageNum: this.page.pageNum,
        roleName: this.ruleForm.roleName,
      };
      getRoleLists(params).then((res) => {
        this.tableData = res.records;
        this.total = res.total;
      });
    },
    getAuthTreeList() {
      getAuthTree().then((res) => {
        this.powerData = res.menuList;
        this.resetCheck(this.powerData);
      });
    },
    //权限配置
    async singleDetail(row) {
      this.dialogVisible = true;
      // this.detailInfo = row;
      this.detailInfo = await getRoleDetailById({ id: row.id });
      this.$nextTick(() => {
        this.setTreeValue(this.powerData);
      });
    },
    setTreeValue(row) {
      row.forEach((e) => {
        if (this.detailInfo.roleMenu.includes(e._id)) {
          this.$set(e, "checkFlag", true);
        } else {
          this.$set(e, "checkFlag", false);
        }
        if (e.permissions && e.permissions.length) {
          e.permissions.forEach((o) => {
            if (this.detailInfo.roleAuth.includes(o.authValue)) {
              e.checkList.push(o.authValue);
            }
          });
        }
        if (e.children && e.children.length) {
          this.setTreeValue(e.children);
        }
      });
    },
    addData() {
      this.dialogTitle = "新增角色";
      this.forms.roleName = "";
      this.forms.roleDesc = "";
      this.forms.orgCode = "";
      this.dialogVisibleEnd = true;
    },
    editData(val) {
      this.dialogTitle = "修改角色";
      this.dialogVisibleEnd = true;
      this.forms.roleName = val.roleName;
      this.forms.roleDesc = val.roleDesc;
      this.id = val._id;
    },
    _addRole(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          saveRole({
            roleName: this.forms.roleName,
            roleDesc: this.forms.roleDesc,
            // orgCode: this.forms.orgCode,
          }).then((res) => {
            this.dialogVisibleEnd = false;
            this.$message.success("新增成功！");
            this.getList();
          });
        } else {
          return false;
        }
      });
    },
    _editRole(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateRole({
            roleName: this.forms.roleName,
            roleDesc: this.forms.roleDesc,
            id: this.id,
          }).then((res) => {
            this.dialogVisibleEnd = false;
            this.$message.success("操作成功！");
            this.getList();
          });
        }
      });
    },
    submitform(formName) {
      if (this.dialogTitle === "新增角色") {
        this._addRole(formName);
      } else {
        this._editRole(formName);
      }
    },
    delData(val) {
      this.$confirm("确认删除该条数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteRole(val.id).then((res) => {
            this.$message.success("删除成功！");
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //权限配置保存
    async submitTree() {
      this.roleMenu = [];
      this.roleAuth = [];
      await this.getTreeValue(this.powerData);
      let data = {
        roleMenu: this.roleMenu,
        dataAuthIds: this.detailInfo.dataAuthIds,
        roleAuth: this.roleAuth,
        defaultAuthId: this.detailInfo.defaultAuthId,
        id: this.id,
      };
      await saveRoleAuth(data);
      this.$message({
        type: "success",
        message: "修改成功",
      });
      this.resetCheck(this.powerData);
      this.dialogVisible = false;
      this.getList();
    },
    getTreeValue(row) {
      row.forEach((e) => {
        if (e.checkFlag) {
          this.roleMenu.push(e._id);
        }
        if (e.checkList && e.checkList.length) {
          this.roleAuth.push(...e.checkList);
        }
        if (e.children && e.children.length) {
          this.getTreeValue(e.children);
        }
      });
    },
    dialogClose() {
      this.resetCheck(this.powerData);
      this.dialogVisible = false;
    },
    resetCheck(row) {
      row.forEach((e) => {
        // e.checkFlag = false;
        this.$set(e, "checkFlag", false);
        if (e.children && e.children.length) {
          this.resetCheck(e.children);
        } else if (e.permissions && e.permissions.length) {
          e.checkList = [];
        }
      });
    },
    // 菜单改变
    checkChange(val, row) {
      this.childCheck(row, val); // 菜单勾选
      this.parentCheck(row, val); // 菜单勾选
      this.authCheck(row, val); // 操作权限
      this.$set(row, "checkFlag", val);
    },
    childCheck(row, val) {
      if (row.children && row.children.length) {
        row.children.forEach((e) => {
          this.$set(e, "checkFlag", val);
          if (e.children && e.children.length) {
            this.childCheck(e, val);
          }
        });
      }
    },
    authCheck(row, flag) {
      if (row.permissions && row.permissions.length) {
        if (flag) {
          const list = row.permissions.map((o) => {
            return o.authValue;
          });
          row.checkList = list || [];
        } else {
          row.checkList = [];
        }
      } else if (row.children && row.children.length) {
        // this.authCheck(row.children);
        row.children.forEach((e) => {
          this.authCheck(e, flag);
        });
      }
    },
    parentCheck(row, flag) {
      let checkFlag = false;
      // 查出系统级应用
      let sysData = this.powerData.find(
        (e) => e.value == row.clientId || e.value == row.value
      );
      this.$nextTick(() => {
        sysData.children.forEach((e) => {
          // 系统内查找是否存在子集（后台管理首页不存在子集，但有按钮权限）
          if (e.children && e.children.length) {
            // 系统内有子集，则循环，
            let hasCheckFlag = e.children.some((o) => {
              return o.checkFlag;
            });
            // 判断孙子集内是否存在 选中 的值
            if (hasCheckFlag) {
              // 存在选中的，则让父级勾选上 结束循环
              this.$set(e, "checkFlag", true);
              checkFlag = true;
            } else {
              this.$set(e, "checkFlag", false); // 不存在则取消父级勾选
            }
          } else {
            // 对于没有子集的集合，按照一级菜单处理，即flag为true，应用级则勾选 或者就取消勾选
            if (e.checkList && e.checkList.length) {
              return true;
            }
          }
        });

        if (flag || checkFlag) {
          // 子集内存在勾选中数据 ，则让应用级也勾选上
          this.$set(sysData, "checkFlag", true);
        } else {
          // 子集内不存在勾选中数据 ，则让应用级取消勾选上
          this.$set(sysData, "checkFlag", false);
        }
      });
    },
    // 权限改变
    handleChange(event, row) {
      if (!row.checkList.length) {
        // this.$set(row, "checkFlag", false);
      } else {
        this.$set(row, "checkFlag", true);
      }
      this.parentCheck(row);
    },
  },
};
</script>

<style lang="less" scoped>
#role {
  padding: 0 20px;
  background: #fff;
  height: 100%;
  .dialog-title {
    text-align: center;
  }
  .line {
    display: flex;
    // align-items: center;
  }
  ::v-deep .authSetDialog {
    .el-dialog {
      margin-top: 80px !important;
      width: 1400px;
    }
    .authTable {
      height: 300px;
    }
  }
  //   .dialog-content {
  //     height: 500px;
  //     overflow: scroll;
  //   }
  ::v-deep .el-table {
    .el-table__row--level-0 {
      .el-table__cell {
        background-color: #cae7fa !important;
      }
    }
    .cell {
      .el-table__expand-icon {
        display: none;
      }
      .el-table__placeholder {
        display: none;
      }
    }
  }
}
</style>
